package handler

import (
	"aiRole/internal/dao/model"
	"aiRole/internal/dao/query"
	result "aiRole/internal/dto/reslult"
	"aiRole/internal/dto/response"
	initSystem "aiRole/pkg/init"
	"aiRole/pkg/util"
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"strconv"
	"time"
)

func (session SessionHandler) AddSession(c *gin.Context) {
	uid := util.GetUserInfo(c).ID
	roleId, err := strconv.ParseInt(c.Param("roleId"), 10, 64)
	if err != nil {
		initSystem.Logger.Error(err.Error())
		result.Error(c, 500, "参数错误")
		return
	}
	//查询角色信息
	characterDB := query.Use(initSystem.DB).Character
	character, err := characterDB.WithContext(context.Background()).Where(characterDB.ID.Eq(roleId)).Omit(characterDB.Prompt).First()
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		result.Error(c, 500, "服务器错误")
		return
	}
	conversationDB := query.Use(initSystem.DB).Conversation
	var conversation model.Conversation
	conversation.UserID = uid
	conversation.CharacterID = roleId
	t := time.Now().Local()
	conversation.LastInteraction = &t
	err = conversationDB.WithContext(context.Background()).Save(&conversation)
	if err != nil {
		result.Error(c, 500, "创建会话失败")
		return
	}
	var responseResult response.SaveSessionResponse
	responseResult.SessionId = conversation.ID
	responseResult.Describe = character.Description
	responseResult.Role = *character
	result.Ok(c, responseResult)
}

func (session SessionHandler) List(c *gin.Context) {
	info := util.GetUserInfo(c)
	conversationDB := query.Use(initSystem.DB).Conversation
	// 1. 查出所有会话
	list, err := conversationDB.WithContext(c).
		Where(conversationDB.UserID.Eq(info.ID)).
		Order(conversationDB.LastInteraction.Desc()).
		Find()
	if err != nil {
		result.Error(c, 500, "服务器错误")
		return
	}

	// 2. 收集所有会话ID
	var ids []int64
	for _, v := range list {
		ids = append(ids, v.ID)
	}
	var rstList []response.SessionListResponse
	characterDB := query.Use(initSystem.DB).Character

	for _, v := range list {
		var item response.SessionListResponse
		item.SessionId = v.ID
		character, err := characterDB.WithContext(context.Background()).
			Where(characterDB.ID.Eq(v.CharacterID)).
			Omit(characterDB.Prompt).First()
		if err != nil {
			result.Error(c, 500, "服务器错误")
			return
		}
		if errors.Is(err, gorm.ErrRecordNotFound) || character == nil || character.ID == 0 {
			continue
		}
		item.RoleId = character.ID
		item.RoleName = character.Name
		item.RoleAvatarUrl = character.AvatarURL
		rstList = append(rstList, item)
	}
	result.Ok(c, rstList)
}

func (session SessionHandler) ById(c *gin.Context) {
	id := c.Param("id")
	sessionId, err := strconv.ParseInt(id, 10, 64)
	if err != nil {
		result.Error(c, 500, "参数错误")
		return
	}
	conversationDB := query.Use(initSystem.DB).Conversation
	sessionInfo, err := conversationDB.WithContext(context.Background()).Where(conversationDB.ID.Eq(sessionId)).First()
	if err != nil {
		result.Error(c, 500, "服务器错误")
		return
	}
	result.Ok(c, sessionInfo)
}
